import KoaRouter from 'koa-router'
import userRouter from './router/user'
import session from 'koa-session2'
import KoaLogger from 'koa-logger'
import KoaJson from 'koa-json'
import KoaCompress from 'koa-compress'
import serve from 'koa-static'
import Koa from 'koa'
import path from 'path'
import webpack from 'webpack'
import config from '../../build/webpack.dev.conf'
import { devMiddleware, hotMiddleware } from 'koa2-webpack-middleware-plus'
import historyApiFallback from 'koa2-connect-history-api-fallback'
import returnCode from "./common/returnCode"
import koaBody from 'koa-body'
import { login } from './middleware/login'
import loginRouter from './router/login'
import indexRouter from './router/index'
let Ut = require("./middleware/sleep");

const app = new Koa()

app.use(historyApiFallback({whiteList: ['/api']}))
// app.keys = ['koaSecret']
app.use(session({
    key: 'SESSION'
}))
app.use(KoaLogger())
app.use(KoaJson())
app.use(serve(path.join(__dirname, 'src/server/public/')))
app.use(KoaCompress({threshold: 2048}))
app.use(koaBody())

if (app.env === 'development'){
    const compiler = webpack(config)
    app.use(devMiddleware(compiler, {
        quiet: false,
        stats: {colors: true},
    }))
}

app.use(async (ctx,next) => {
    try{
        ctx.session.username="测试"
        const start = new Date().getTime()
        await next()
        // await Ut.sleep(3000)
        const ms = new Date().getTime() - start
        console.log(`Time: ${ms}ms`)
    }catch(err){
        // ctx.status = err.statusCode || err.status || 500
        switch (err.name) {
            case 'SequelizeValidationError':
                returnCode.VALIDATEERROR.message = err.message
                ctx.body = returnCode.VALIDATEERROR
                break
            case 'SequelizeUniqueConstraintError':
                returnCode.VALIDATEERROR.message = err.message
                ctx.body = returnCode.VALIDATEERROR
                break
            default:
                ctx.status = err.status || 500
                ctx.body = {
                    code: err.status || 500,
                    type: '服务器出错',
                    message: '服务器出错'
                }
        }
        console.log(err)
    }
})

const router = new KoaRouter()
router.use('/api', indexRouter.routes())
router.use('/api', loginRouter.routes())
router.use('/api', userRouter.routes())
// router.use('/api', login, userRouter.routes())
// router.use(indexRouter.routes())
app.use(router.routes())


const SERVER_PORT = 3000
app.listen(SERVER_PORT, () => {
    console.log(`server listen on http://localhost:${SERVER_PORT}`)
})
